import {getToken, setToken} from "@/utils/auth"
import {getInfo} from "@/api/user";

const state = {
    token: getToken(),
    name: '',
    roles: []
}

const actions = {
    login({commit},userInfo){
      const {token} = userInfo;
        commit('SET_TOKEN', token);
        // 持久化
        setToken(token);

     },

    // get user info
    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
             getInfo(state.token).then(response => {
                if (!response) {
                    reject('Verification failed, please Login again.')
                }

                 const { roles, name } = response

                // roles must be a non-empty array
                if (!roles || roles.length <= 0) {
                    reject('getInfo: roles must be a non-null array!')
                }

                commit('SET_ROLES', roles)
                commit('SET_NAME', name)
                resolve(response)
            }).catch(error => {
                reject(error)
            })
        })
    },

}

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_ROLES: (state, roles) => {
        state.roles = roles
    }
}

export default {
    namespaced: true,
    state,
    actions,
    mutations,

}
